<template>
  <el-card class="page_card">
    <el-form :inline="true" class="form">
      <el-form-item label="教师账户：">
        <el-input v-model="data.queryForm.username" placeholder="请输入教师账户"></el-input>
      </el-form-item>
      <el-form-item label="教师姓名：">
        <el-input v-model="data.queryForm.realname" placeholder="请输入教师姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" color="#626aef" @click="search"
          :disabled="(!data.queryForm.username && !data.queryForm.realname) ? true : false">搜索</el-button>
        <el-button @click="reset" color="#626aef" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" icon="Plus" @click="addUser">添加教师</el-button>
    <el-button type="danger" :disabled="data.selectIdArr.length ? false : true" @click="deleteSelectUser">批量删除</el-button>
    <el-table style="margin: 10px 0;" border :data="data.userTableData" @selection-change="selectionChange" max-height="663">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index" :width="80"></el-table-column>
      <el-table-column label="教师账户" align="center" prop="username"></el-table-column>
      <el-table-column label="教师姓名" align="center" prop="realname"></el-table-column>
      <el-table-column label="性别" align="center" prop="gender"></el-table-column>
      <el-table-column label="所属角色" align="center" prop="roleId" :formatter="roleFormatter"></el-table-column>
      <el-table-column label="创建时间" align="center" show-overflow-tooltip>
        <template #default="scope">{{ scope.row.createTime?.slice(0, 10) }}</template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" show-overflow-tooltip>
        <template #default="scope">{{ scope.row.updateTime?.slice(0, 10) }}</template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="160px">
        <template #default="scope">
          <el-switch v-model="scope.row.active" :active-value="1" :inactive-value="0" active-text="启用"
            inactive-text="停用" @change="changeStatus($event, scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="270px" align="center">
        <template #="{ row }">
          <el-button type="primary" link icon="User" @click="assignRole(row)">分配角色</el-button>
          <el-button type="primary" link icon="Edit" @click="updateUser(row)">编辑</el-button>
          <el-popconfirm :title="`确认删除${row.username}吗？`" width="260px" @confirm="deleteUser(row)">
            <template #reference>
              <el-button type="danger" link icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination 
      v-model:current-page="data.currentPage" 
      v-model:page-size="data.pageSize"
      :page-sizes="[10, 20, 30, 40]" 
      :background="true" 
      layout="->,prev, pager, next, jumper,sizes,total"
      :total="data.total" 
      @current-change="currentChange"
      @size-change="sizeChange"
    />
  </el-card>
  <!-- 添加教师、修改教师 -->
  <el-dialog v-model="data.addUserDialog" :title="data.userForm.id ? '更新教师' : '添加教师'" width="650">
    <el-form :model="data.userForm" :rules="rules" ref="formRef" label-width="130px" style="max-width: 550px">
      <el-form-item label="教师账户" prop="username">
        <el-input v-model="data.userForm.username" placeholder="请输入教师账户" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="教师姓名" prop="realname">
        <el-input v-model="data.userForm.realname" placeholder="请输入教师姓名" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="data.userForm.password" placeholder="请输入用户密码" type="password" show-password
          autocomplete="new-password"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="data.userForm.gender">
          <el-radio value="男">男</el-radio>
          <el-radio value="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.addUserDialog = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 分配角色 -->
  <el-dialog v-model="data.assignRoleDialog" title="分配教师角色" width="650">
    <el-form label-width="130px" style="max-width: 550px">
      <el-form-item label="教师姓名">
        <el-input v-model="data.userForm.realname" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="角色列表">
        <el-select v-model="data.userForm.roleId" placeholder="请选择角色" @change="roleIdChange">
          <el-option v-for="item in data.roleList" :key="item.id" :label="item.realName" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.assignRoleDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqAllUser, reqAddOrUpdateUser, reqRemoveUser, reqRemoveUsers, reqChangeActive, reqAllRole } from '@/api/sys/userApi'
import type { UserResData, User } from '@/api/sys/userType'
import type { Role } from '@/api/sys/roleType'
import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '@/store/modules/setting'
import { GET_USERINFO,SET_USERINFO } from "@/utils/token"; //本地存储方法
import {reqGetMenuByUserName} from '@/api/sys/roleApi'
import useUserStore from '@/store/modules/user';

let userStore = useUserStore()
let settingStore = useLayOutSettingStore() // 模板setting仓库
let formRef = ref<any>() //form组件实例
const data = reactive({
  queryForm: {
    username: '',
    realname: '',
  },
  userTableData: [] as User[],
  currentPage: 1,
  pageSize: 10,
  total: 0,
  addUserDialog: false, //新增对话框
  userForm: { //新增表单
    userType: '1',
    username: '', //教师账户
    realname: '', //教师姓名
    password: '',  //密码
    gender: '男', //性别
    roleId:'', //分配角色id
    id: '',
    roleName:'', //角色编码
    roleRealName:'', //角色名称
  },
  selectIdArr: [],//批量删除勾选的用户id
  assignRoleDialog: false, //分配角色对话框
  roleList: [] as Role[],
  defauleRole:{} as Role | undefined, //新增用户默认超级管理员角色
})

onMounted(() => {
  initRoleSelect()
  initUserData()
})

// 所属角色map对象
// @ts-ignore
const roleFormatter = (row, column, cellValue) => {
  const roleMap:any = data.roleList.reduce((acc:any, cur:any) => {  
  acc[cur.id] = cur.realName 
  return acc 
}, {});  
  return roleMap[cellValue] || ''
}

// 获取全部角色列表
const initRoleSelect = async () => {
  let res = await reqAllRole()
  if (res.code == 200) {
    data.roleList = res.data.records.filter((item:any) => item.roleName !== 'common_role')
    data.defauleRole = data.roleList.find(option => option.roleName === 'admin_role')
  }
}
// 状态 启用/停用
const changeStatus = async (event: number, row: User) => {
  let params = {
    id: row.id,
    active: event,
    version: row.version
  }
  let res = await reqChangeActive(params)
  if (res.code == 200) {
    ElMessage.success(event == 0 ? '停用成功！' : '启用成功！')
    initUserData()
  } else {
    ElMessage.error(res.msg)
  }
}
// 分配角色
const assignRole = async (row: User) => {
  Object.assign(data.userForm, row)
  data.assignRoleDialog = true
}
// 分配角色确认按钮
const confirmClick = async () => {
  try {
    let res: any = await reqAddOrUpdateUser(data.userForm)
    if (res.code == 200) {
      data.assignRoleDialog = false
      ElMessage.success('分配角色成功！')
      initUserData()
      setUserMenuInfo() // 分配角色后，刷新本地存储的用户菜单权限
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) { }
}
// 角色列表下拉框切换
const roleIdChange = (value: any) => {
  const selectedOption:any = data.roleList.find(option => option.id === value)
  data.userForm.roleName = selectedOption.realName
  data.userForm.roleRealName = selectedOption.roleName
}
// 分配角色后，刷新本地存储的用户菜单权限
const setUserMenuInfo = async() => {
  let res = await reqGetMenuByUserName(userStore.username)
  if(res.code==200){
    let userInfo = GET_USERINFO()
    userInfo.menuList = res.data
    SET_USERINFO(userInfo) // 更新用户信息
  }
}

// 搜索
const search = () => {
  initUserData()
}
// 重置
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}
// 获取教师列表
const initUserData = async (pager = 1) => {
  data.currentPage = pager
  let params = {
    current: data.currentPage,
    size: data.pageSize,
    userType: '1',
    ...data.queryForm
  }
  let res: UserResData = await reqAllUser(params)
  if (res.code == 200) {
    data.userTableData = res.data.records
    data.total = res.data.total
  }
}
// 分页器下拉事件
const currentChange = () => {
  initUserData(data.currentPage)
}
const sizeChange = ()=> {
  initUserData()
}
const addUser = () => {
  // 新增用户默认超级管理员角色
  data.addUserDialog = true
  // 清空数据
  Object.assign(data.userForm, {
    userType: '1',
    username: '', //教师账户
    realname: '', //教师姓名
    password: '',  //密码
    gender: '男', //性别
    roleId:data.defauleRole?.id, //分配角色id
    id: '',
    roleName:data.defauleRole?.roleName, //角色编码
    roleRealName:data.defauleRole?.realName, //角色名称
  })
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('realname')
    formRef.value.clearValidate('password')
  })
}
const updateUser = (row: User) => {
  data.addUserDialog = true
  Object.assign(data.userForm, row)
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('realname')
    formRef.value.clearValidate('password')
  })
}
// 新增用户确认按钮
const save = async () => {
  try {
    await formRef.value.validate()
    let res: any = await reqAddOrUpdateUser(data.userForm)
    if (res.code == 200) {
      data.addUserDialog = false
      ElMessage.success(data.userForm.id ? '更新成功！' : '添加成功！')
      initUserData()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) { }
}
// @ts-ignore
const validatorUsername = (rule: any, value: any, callBack: any) => {
  // 用户名至少5位
  if (value.trim().length >= 3) {
    callBack()
  } else {
    callBack(new Error('教师账户至少3位'))
  }
}
// @ts-ignore
const validatorPassword = (rule: any, value: any, callBack: any) => {
  // 用户名至少5位
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('密码至少6位'))
  }
}
// 表单校验规则对象
const rules = {
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  realname: [{ required: true, trigger: 'blur', message: '请输入教师姓名' }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
// 删除单行用户
const deleteUser = async (row: User) => {
  let res = await reqRemoveUser((row.id as number), row.version)
  if (res.code == 200) {
    ElMessage.success('删除成功！')
    initUserData(data.userTableData.length == 0 ? 1 : data.currentPage)
  } else {
    ElMessage.error('删除失败！')
  }
}
// table复选框勾选事件
const selectionChange = (value: any) => {
  data.selectIdArr = value
}
// 批量删除
const deleteSelectUser = async () => {
  let ids = data.selectIdArr.map((item: any) => item.id).join(',')
  let versions = data.selectIdArr.map((item: any) => item.version).join(',')
  let res = await reqRemoveUsers(ids, versions)
  if (res.code == 200) {
    ElMessage.success('批量删除成功！')
    initUserData(data.userTableData.length == 0 ? 1 : data.currentPage)
  } else {
    ElMessage.error(res.msg)
  }
} 
</script>

<style scoped lang="scss"></style>
